package com.example.demo.utils.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.constant.WxTemplateSend;
import com.example.demo.utils.HttpUtils;
import com.example.demo.utils.template.Miniprogram;
import com.example.demo.utils.template.TemplateData;
import com.example.demo.utils.template.WxTemplateMsg;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WxTemplateUtils {

    private static final Logger logger = LoggerFactory.getLogger(WxTemplateUtils.class);


    /**
     * 微信模板消息推送工具类
     * 2018年3月17日 下午4:36:57   todo json 转obj 还得改改
     *
     * @author qzh
     */
    public static WxTemplateResult sendTimeerMsg(String nickName, String openId, String wxToken, String data, String url, String pushTmpl) throws IOException {
        //获取data
        String firstValue = JSONObject.parseObject(JSONObject.parseObject(data).getString("first")).getString("value");
        String firstColor = JSONObject.parseObject(JSONObject.parseObject(data).getString("first")).getString("color");
        String goodValue = JSONObject.parseObject(JSONObject.parseObject(data).getString("Good")).getString("value");
        String goodColor = JSONObject.parseObject(JSONObject.parseObject(data).getString("Good")).getString("color");
        String contentTypeValue = JSONObject.parseObject(JSONObject.parseObject(data).getString("contentType")).getString("value");
        String contentTypeColor = JSONObject.parseObject(JSONObject.parseObject(data).getString("contentType")).getString("color");
        String remarkValue = JSONObject.parseObject(JSONObject.parseObject(data).getString("remark")).getString("value");
        String remarkColor = JSONObject.parseObject(JSONObject.parseObject(data).getString("remark")).getString("color");
        //------------------模板推送-------------------
        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
        //推送模板
        wxTemplateMsg.setTemplate_id(pushTmpl);
        wxTemplateMsg.setTouser(openId);
        Map<String, TemplateData> map = new HashMap<>();
        TemplateData first = new TemplateData();
        first.setColor(firstColor);
        first.setValue(firstValue);
        map.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setValue(goodValue);
        keyword1.setColor(goodColor);
        if ("c5pp3brlfAvsyw1Xd8a_sw8DuuSAWLfyLNkgxQhkGqU".equals(pushTmpl)) {
            map.put("Good", keyword1);
        } else {
            map.put("keyword1", keyword1);
        }
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor(contentTypeColor);
        keyword2.setValue(contentTypeValue);
        if ("c5pp3brlfAvsyw1Xd8a_sw8DuuSAWLfyLNkgxQhkGqU".equals(pushTmpl)) {
            map.put("contentType", keyword2);
        } else {
            map.put("keyword2", keyword2);
        }
        TemplateData remark = new TemplateData();
        remark.setColor(remarkColor);
        remark.setValue(remarkValue);
        map.put("remark", remark);
        wxTemplateMsg.setData(map);
        wxTemplateMsg.setUrl(url);
        String result = HttpUtils.doPostJson(WxConfig.TEMPLATE_SEND_URL.replace("ACCESS_TOKEN", wxToken), JSON.toJSONString(wxTemplateMsg));
        WxTemplateResult wxTemplateResult = (WxTemplateResult) JSONObject.parseObject(JSONObject.parseObject(result).toString(), WxTemplateResult.class);
        if (StringUtils.isNotBlank(result)) {
            if (wxTemplateResult.getErrcode() != 0) {
                logger.info("error::" + wxTemplateResult.getErrmsg());
            }
            return wxTemplateResult;
        }
        return null;
    }


    public static WxTemplateResult sendData(String openId, String shareTimes, String readTimes,String nickName, String wxToken) throws IOException {
        //------------------模板推送-------------------
        String twoDays = getBeforeOrAfterDate(2)+" ～ "+getBeforeOrAfterDate(1);
        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
        //推送模板
        wxTemplateMsg.setTemplate_id("nFgF_BkHguYB44H89Tq_OiKs_WW5Y_ffk2sUZYqvWpM");
        wxTemplateMsg.setTouser(openId);
        Map<String, TemplateData> map = new HashMap<>();
        TemplateData first = new TemplateData();
        first.setColor("#3a6fae");
        first.setValue("线上展业需要更多的坚持，只有多使用，增加曝光次数，我们才有更多机会获客签单!\n\n数据汇总："+twoDays+"\n\n两日内总计分享量："+ shareTimes +" 次\n两日内阅读准客户："+ readTimes +" 人次    ");
        map.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setColor("#000000");
        keyword1.setValue(nickName+"老师");
        map.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor("#000000");
        keyword2.setValue(now()+"   ");
        map.put("keyword2", keyword2);
        TemplateData remark = new TemplateData();
        remark.setColor("#c4381e");
        remark.setValue("回复\"9\"查看今日更新素材   ");
        map.put("remark", remark);
        wxTemplateMsg.setData(map);
        wxTemplateMsg.setUrl("http://one.wcwlvip.com");
//        todo 等待通知，模板是否加上小程序跳转连接
//        Miniprogram miniprogram = new Miniprogram();
//        miniprogram.setAppid("wx9adaaa30063a52cb");
//        miniprogram.setPagepath("pages/index/index");
//        wxTemplateMsg.setMiniprogram(miniprogram);
        String result = HttpUtils.doPostJson(WxConfig.TEMPLATE_SEND_URL.replace("ACCESS_TOKEN", wxToken), JSON.toJSONString(wxTemplateMsg));
        WxTemplateResult wxTemplateResult = (WxTemplateResult) JSONObject.parseObject(JSONObject.parseObject(result).toString(), WxTemplateResult.class);
        if (StringUtils.isNotBlank(result)) {
            if (wxTemplateResult.getErrcode() != 0) {
                logger.info("error::" + wxTemplateResult.getErrmsg());
            }
            return wxTemplateResult;
        }
        return null;
    }

    private static String now() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }


    public static String getBeforeOrAfterDate(int num) {
        num = num * -1;
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        Calendar calendar = Calendar.getInstance();//获取日历
        calendar.setTime(new Date());//当date的值是当前时间，则可以不用写这段代码。
        calendar.add(Calendar.DATE, num);
        Date d = calendar.getTime();//把日历转换为Date
        return sdf.format(d);
    }

    public static void main(String[] args) {
        try {
            String token = HttpUtils.getAccessToken();
            sendData("ogKxFwGaNpF1yaXKSGnU-chtCw3U","10","20","chen",token);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
